package com.rent.user.util;

import com.rent.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Random;

/**
 * 验证码工具类
 */
@Slf4j
@Component // 交给Spring管理
public class CodeUtil {

    @Resource
    private RedisUtil redisUtil;

    // 短信验证码相关常量
    private static final String SMS_CODE_PREFIX = "sms:code:";

    /**
     * 生成随机验证码
     *
     * @param length 验证码长度
     * @return 验证码字符串
     */
    public static String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送短信验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean sendCode(String phone, String code) {
        try {
            // 模拟发送，在控制台打印验证码
            log.info("【短信验证码】手机号: {}, 验证码: {}, 有效期: 5分钟", phone, code);

            // 在控制台显眼地打印验证码，方便测试
            System.out.println("==========================================");
            System.out.println("短信验证码（开发环境）");
            System.out.println("手机号: " + phone);
            System.out.println("验证码: " + code);
            System.out.println("有效期: 5分钟");
            System.out.println("==========================================");

            // 模拟网络延迟
            Thread.sleep(100);

            // 直接返回成功
            return true;
        } catch (Exception e) {
            log.error("模拟发送短信异常: phone={}", phone, e);
            return false;
        }
    }

    /**
     * 验证短信验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean verifySmsCode(String phone, String code) {
        try {
            String redisKey = SMS_CODE_PREFIX + phone;
            String storedCode = (String) redisUtil.get(redisKey);

            if (storedCode == null) {
                log.info("验证码已过期: phone={}", phone);
                return false;
            }

            boolean isValid = storedCode.equals(code);
            if (!isValid) {
                log.info("验证码不匹配: phone={}, input={}, stored={}", phone, code, storedCode);
            }

            return isValid;
        } catch (Exception e) {
            log.error("验证短信验证码异常: phone={}", phone, e);
            return false;
        }
    }
}